import axios from 'axios'
import qs from 'qs'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // timeout: 1000 * 60 * 100, // request timeout
  headers: {
    'content-type': 'application/x-www-form-urlencoded'
  }
})
// 允许跨域携带cookie
service.defaults.withCredentials = true;
// 请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if(config.method === 'post') {
      if(config.url.indexOf('/seck/addList') == -1 && config.url.indexOf('/seck/updateList') == -1) {
        config.data = qs.stringify(config.data)
      }
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    console.log(res)
    if (res.code && res.code.toString() === '401') {
      // 清除localStorage 跳出网站
      // 清除与登录信息相关的local storage
      localStorage.removeItem("isLogin");
      localStorage.removeItem("baseInfo");
      localStorage.removeItem("proInfo");
      localStorage.removeItem("proUserFile");
      localStorage.removeItem("generalUserInfo");
      localStorage.removeItem("testId");
      // 清除session storage
      sessionStorage.clear();
      // 删除保存在cookie里的token
      console.log(window.location.href)
      console.log(document.domain)
      // alert('出现了401情况')
      document.cookie = "WAIMS_TOKEN" + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
      if(window.location.href.indexOf('https://xn--15t241ax9eqv8a.xn--fiqs8s/psych') > -1 ) {
        window.location.href = "https://xn--15t241ax9eqv8a.xn--fiqs8s/"
      } else if (window.location.href.indexOf('https://psychological-assessment.com/psych') > -1 ) {
        // 测试环境
        window.location.href = 'https://psychological-assessment.com/'
      } else {
        // 正式环境
        window.location.href = 'https://psychometrics-home.com/'
      }
    }
    return res
  },
  error => {
    console.log('err: ' + error) // for debug
    return Promise.reject(error)
  }
)
export default service
